﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using DouYin.Open.Platform.Tools;

namespace DouYin.Open.Platform.ERP
{
    public class APIRequest : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var query = dataset.GetJsonObject("query");
                var constant = dataset.GetJsonObject("constant");
                
                string eShopCode = query.GetJsonObjectStringValue("access_token");
                string api = query.GetJsonObjectStringValue("api");
                string appkey = query.GetJsonObjectStringValue("app_key");
                string method = query.GetJsonObjectStringValue("method");
                string timestamp = query.GetJsonObjectStringValue("timestamp");
                string version = query.GetJsonObjectStringValue("v", "2");
                string sign = query.GetJsonObjectStringValue("sign");
                string sign_method = query.GetJsonObjectStringValue("sign_method", "hmac-sha256");

                var douyinAPIConfig = constant.GetJsonObject("douyinAPIConfig");
                var eshopAPIConfig = douyinAPIConfig.GetJsonObject("eshops").GetJsonObject(eShopCode);
                string url = douyinAPIConfig.GetJsonObjectStringValue("url");
                var timeout = eshopAPIConfig.GetJsonObjectIntValue("timeout", 60000);
                var proxy = eshopAPIConfig.GetJsonObjectValue("proxy");

                if (string.IsNullOrWhiteSpace(eShopCode))
                    throw new BaseException("@20001", "");

                if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(appkey))
                    throw new BaseException("@20002", "");

                if (string.IsNullOrWhiteSpace(method) || string.IsNullOrWhiteSpace(timestamp) || string.IsNullOrWhiteSpace(sign))
                    throw new BaseException("@20003", "");
                
                string accessToken = GetAccessToken.GetToken(eShopCode, constant);
                string strParam = dataset.GetJsonObjectStringValue("requestString");


                if (!url.EndsWith("/"))
                    url = url + "/";
                if (string.IsNullOrWhiteSpace(api))
                    api = method.Replace(".", "/");
                else if (api.StartsWith("/"))
                    api = api.Trim('/');
                url = string.Format("{0}{1}?app_key={2}&method={3}&v={4}&sign={5}&timestamp={6}&access_token={7}&sign_method={8}", url, api, appkey, method, version, sign, timestamp, accessToken, sign_method);
                var headers = new System.Collections.Generic.Dictionary<string, string>() { { "content-type", "application/json" } };
                //LogHelper.Info("url: " + url);
                //LogHelper.Info("request: " + strParam);
                string responseString = HttpHelper.HttpWebRequest(url, strParam, "POST", timeout, headers, proxy?.ToString());
                //LogHelper.Info("response: " + responseString);

                try
                {
                    return JToken.Parse(responseString);
                }
                catch (Exception ex)
                {
                    LogHelper.Info(responseString);
                    throw ex;
                }
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Error("DouYin APIRequest Fail", ex);
                throw new Exception("@20000");
            }
        }
    }
}
